package cn.pa4j.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.pa4j.dao.LpDao;
import cn.pa4j.pojo.Administartor;
import cn.pa4j.pojo.User;
import top.jsnow.controller.Controller;
import top.jsnow.controller.annotation.GetAction;
import top.jsnow.controller.annotation.PostAction;
import top.jsnow.db.Dao;
import top.jsnow.db.DaoMgr;
import top.jsnow.http.Session;

import java.util.List;

/**
 * Created by 060016 on 2017-11-29.
 */
public class AdminController extends Controller {

    @GetAction
    public void loginform() {
    }

    @GetAction("/home")
    public void home() {
    }

    //登录
    @PostAction("/admin/login")
    public JSONObject userlogin(String username, String password) {
        Session session = req.session();
        LpDao dao = new LpDao();
        dao.init();
        JSONObject result = new JSONObject();
        //临时用户
        Administartor user = dao.getAdministartorByName(username);
//        if ("admin".equals(username)) {
//            user = new Administartor("admin", "123");
//        }

        if (null == user) {
            result.put("status", "404");
            result.put("msg", "用户名不存在！");
            return result;
        }

        System.out.println(user);

        if (password.equals(user.getPassword())) {
            session.put("username", username);
            result.put("status", "200");
            return result;
        } else {
            result.put("status", "500");
            result.put("msg", "密码错误！");
            return result;
        }
    }

    @GetAction("/governor/user/add")
    public void adduserform() {
    }
    @GetAction("/governor/user/all")
    public void alluser() {
    }
    @PostAction("/governor/user/addUser")
    public JSONObject addUser(String json){
        JSONObject result = new JSONObject();
        User user = JSONUtil.toBean(JSONUtil.parseObj(json), User.class);
        try {
            LpDao dao = new LpDao();
            dao.addUser(user);
            result.put("status", "200");
            return result;
        }catch (Exception e){
            result.put("status", "500");
            result.put("msg", "错误！");
            return result;
        }

    }
    @GetAction("/user/users")
    public JSONArray getAllUsers(){
        LpDao dao = new LpDao();
        List<User> userList = dao.getAllUsers();
        JSONArray array = new JSONArray(userList);
        return array;
    }
//    @PostAction("/user/delete/{userId}")
//    public  JSONObject deleteUser(int userId){
//        JSONObject result = new JSONObject();
//        try{
//            dao.deleteUser(userId);
//            result.put("status",1);
//            result.put("msg","删除成功");
//        }catch (Exception e){
//            result.put("status",0);
//            result.put("msg",e.getMessage());
//        }
//        return result;
//    }
}
